import {defineStore} from "pinia";
import {ref} from "vue";
import type {Ref} from "vue";
import type {PwdLoginDTO, SimulateWxLoginDTO, UserInfoDTO, UserInfoVO, WxLoginDTO} from "@/types/loginType";
import {fetchProfileAPI, passwordLoginAPI, simulateLoginAPI, updateProfileAPI, wxLoginAPI} from "@/api/loginAPI";

type LoginType = "passwordLogin" | "wxLogin" | "simulateWxLogin"

const useLoginStore = defineStore("loginStore", () => {

    // 用户信息
    const userInfo: Ref<UserInfoVO> = ref<UserInfoVO>({} as UserInfoVO);

    // 会员信息
    const profileInfo: Ref<UserInfoVO> = ref<UserInfoVO>({} as UserInfoVO);

    // 发送登录请求的回调函数
    const login = async (type: LoginType, data: PwdLoginDTO | WxLoginDTO | SimulateWxLoginDTO): Promise<void> => {
        try {
            if (type === "passwordLogin") {
                const {result} = await passwordLoginAPI(data as PwdLoginDTO);
                userInfo.value = result;
            } else if (type === "wxLogin") {
                const {result} = await wxLoginAPI(data as WxLoginDTO);
                userInfo.value = result;
            } else if (type === "simulateWxLogin") {
                const {result} = await simulateLoginAPI(data as SimulateWxLoginDTO);
                userInfo.value = result;
            } else {
                await uni.showToast({
                    title: "请选择合适的登录方式",
                    icon: "error",
                });
            }
        } catch (error: any) {
            await error;
        }
    };

    // 发送请求获取用户信息的回调函数
    const fetchProfileInfo = async (): Promise<void> => {
        try {
            const {result}: { result: UserInfoVO } = await fetchProfileAPI();
            profileInfo.value = result;
        } catch (error: any) {
            await error;
        }
    };

    //发送请求修改用户信息的回调函数
    const updateProfile = async (data: UserInfoDTO) => {
        try {
            await updateProfileAPI(data)
        } catch (error: any) {
            await error
        }
    }

    // 清空用户信息
    const clearUserInfo = () => {
        userInfo.value = {} as UserInfoVO;
    };

    return {
        userInfo,
        login,
        clearUserInfo,
        profileInfo,
        fetchProfileInfo,
        updateProfile,
    };
}, {
    persist: {
        key: "userInfo",
        paths: ["userInfo"],
        storage: {
            getItem(key) {
                return uni.getStorageSync(key);
            },
            setItem(key, value) {
                uni.setStorageSync(key, value);
            },
        },
    },
});


export default useLoginStore;